//
//  UNPhotosPickerController.m
//  iosapp
//  相册选择图片视频
//  Created by 吴彬 on 15/12/18.
//  Copyright © 2015年 吴彬. All rights reserved.
//

#import "UNPhotosPickerController.h"
#import "UNPhotoPickerListCell.h"
#import "UNPhotoPickerCollectionController.h"
@import Photos;

#define cellHeight 80
#define Column  4
#define capWidth 2

@interface UNPhotosPickerController ()<UITableViewDataSource,UITableViewDelegate,PHPhotoLibraryChangeObserver>
@property(strong,nonatomic)UITableView *tableView;
@property(strong,nonatomic) NSMutableArray *albums;
@property(nonatomic,strong)NSArray *albumTypeAry;
@property(nonatomic,strong)PHFetchOptions *options;
@end

@implementation UNPhotosPickerController

- (instancetype)initWithAlbumType:(NSArray *)albumType
{
    self = [super init];
    if (self) {
        if (albumType) {
            self.albumTypeAry = albumType;
        } else {
            self.albumTypeAry = @[@(PHAssetCollectionSubtypeSmartAlbumUserLibrary),@(PHAssetCollectionSubtypeSmartAlbumRecentlyAdded),@(PHAssetCollectionSubtypeSmartAlbumVideos),@(PHAssetCollectionSubtypeSmartAlbumSelfPortraits),@(PHAssetCollectionSubtypeSmartAlbumScreenshots)];
        }
        self.albums = [[NSMutableArray alloc] init];
        self.options = [[PHFetchOptions alloc] init];
        self.options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
        self.maxNum = 9;
        //获取系统相册以及用户创建相册
        PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
        PHFetchResult *topLevelUserCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
        [smartAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if([self.albumTypeAry containsObject:@(obj.assetCollectionSubtype)]){
                
                PHFetchResult *countResult = [PHAsset fetchAssetsInAssetCollection:obj options:nil];
                if (countResult.count > 0) {
                    [self.albums addObject:obj];
                }
            }
        }];
        
        for (PHCollection *collection in topLevelUserCollections) {
            
            if ([collection isKindOfClass:[PHAssetCollection class]]) {
                PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:(PHAssetCollection *)collection options:nil];
                if (fetchResult && fetchResult.count > 0) {
                    [self.albums addObject:collection];
                }
                
            }
            
        }
    }
    return self;
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //添加tableView
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[UNPhotoPickerListCell class] forCellReuseIdentifier:@"cell"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(backAction)];
    self.title = @"相册";
    //注册相册资源变动观察者
    //    [[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:self];
}

-(void)backAction
{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

-(void)dealloc{
    //    [[PHPhotoLibrary sharedPhotoLibrary] unregisterChangeObserver:self];
}


#pragma mark - PHPhotoLibraryChangeObserver
- (void)photoLibraryDidChange:(PHChange *)changeInstance
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        //        NSMutableArray *updatedCollectionsFetchResults = nil;
        //
        //        for (PHFetchResult *collectionsFetchResult in self.collectionsFetchResults) {
        //            PHFetchResultChangeDetails *changeDetails = [changeInstance changeDetailsForFetchResult:collectionsFetchResult];
        //            if (changeDetails) {
        //                if (!updatedCollectionsFetchResults) {
        //                    updatedCollectionsFetchResults = [self.collectionsFetchResults mutableCopy];
        //                }
        //                [updatedCollectionsFetchResults replaceObjectAtIndex:[self.collectionsFetchResults indexOfObject:collectionsFetchResult] withObject:[changeDetails fetchResultAfterChanges]];
        //            }
        //        }
        //
        //        if (updatedCollectionsFetchResults) {
        //            self.collectionsFetchResults = updatedCollectionsFetchResults;
        //            [self.tableView reloadData];
        //        }
        
    });
}



#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    PHFetchResult *result=nil;
    PHAssetCollection *temp=[self.albums objectAtIndex:indexPath.row];
    result = [PHAsset fetchAssetsInAssetCollection:temp options:self.options];
    if ([result count]<1) {
        return;
    }
    CGFloat screenWidth=[[UIScreen mainScreen] bounds].size.width;
    CGFloat itemLength=(screenWidth-(Column +1) *capWidth)/Column;
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize=CGSizeMake(itemLength, itemLength);
    flowLayout.sectionInset=UIEdgeInsetsMake(capWidth, capWidth,capWidth ,capWidth);
    flowLayout.minimumInteritemSpacing=capWidth;
    flowLayout.minimumLineSpacing=capWidth;
    flowLayout.scrollDirection=UICollectionViewScrollDirectionVertical;
    
    UNPhotoPickerCollectionController *alumnController= [[UNPhotoPickerCollectionController alloc]initWithCollectionViewLayout:flowLayout];
    alumnController.assetsFetchResults=result;
    alumnController.maxNum = self.maxNum;
    alumnController.delegate=self.delegate;
    [self.navigationController pushViewController:alumnController animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return cellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}



#pragma mark - UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *localizedTitle = nil;
    NSUInteger estimatedAssetCount = 0;
    UNPhotoPickerListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    PHAssetCollection *collection = (PHAssetCollection *)self.albums[indexPath.row];
    PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:collection options:self.options];
    
    localizedTitle = collection.localizedTitle;
    estimatedAssetCount = fetchResult.count;
    cell.label.text = [NSString stringWithFormat:@"%@ (%lu)",localizedTitle,(unsigned long)fetchResult.count];
    [fetchResult enumerateObjectsUsingBlock:^(PHAsset *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx < 3 && obj ) {
            [[PHImageManager defaultManager] requestImageForAsset:obj targetSize:CGSizeMake(44, 44) contentMode:PHImageContentModeDefault options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                if (result) {
                    if (idx == 0) {
                        cell.imageV1.image = result;
                        if (obj.mediaType == PHAssetMediaTypeVideo) {
                            cell.videoIcon.hidden = NO;
                        } else {
                            cell.videoIcon.hidden = YES;
                        }
                    } else if (idx == 1) {
                        cell.imageV2.image = result;
                    } else if (idx == 2) {
                        cell.imageV3.image = result;
                    }
                    
                }
                
            }];
        }
    }];

return cell;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger numberOfRows = 0;
    if (self.albums) {
        numberOfRows = self.albums.count;
    }
    return numberOfRows;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//
//延时摄影 assetCollectionType=2/204
//个人收藏 assetCollectionType=2/203
//已隐藏 assetCollectionType=2/205
//相机胶卷 assetCollectionType=2/209
//最近删除 assetCollectionType=2/1000000201
//最近添加 assetCollectionType=2/206
//全景照片 assetCollectionType=2/201
//视频 assetCollectionType=2/202
//慢动作 assetCollectionType=2/208
//连拍快照 assetCollectionType=2/207
//自拍 assetCollectionType=2/210
//屏幕快照 assetCollectionType=2/211
@end
